package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.Time;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: MoneyFlowNewAction
 * 
 * @Description: 实时货币流水
 * @author liuchen
 * @date 2017-5-16 下午3:40:01
 */
@Controller
@Scope("prototype")
@RequestMapping("/flow/moneyFlow")
public class MoneyFlowNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	HadoopQueryManager hadoopQueryManager;

	private Map<String, String> rechargeCurrencyItmes = GameParamConfigManager
			.getItems(CommonGameParam.RECHARGE_CURRENCY_TYPE); // 充值相关类型



	@RequestMapping(value = "updateServer.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateServer(HttpServletRequest request, HttpServletResponse response, String serverid, String callback) {
		try {
			queryServer = serverid;
			selectServerItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updateChannel.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channelid,
			String callback) {
		try {
			queryChannel = channelid;
			selectChannelItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "updatePlatform.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platformid,
			String callback) {
		try {
			queryPlatform = platformid;
			selectPlatformItems();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	/**
	 * 
	 * @Description: TODO 获取参数
	 * @param @param request
	 * @param @param response
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			result.put("typeItmes", GameParamConfigManager.getItems(CommonGameParam.CURRENCY_TYPE));
			Map<String, String> t = new LinkedHashMap<>();
			t.put("全部", GameParamConfigManager.ALL_FLAT);
			result.put("reasonItmes", t);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	/**
	 * 
	 * @Description: TODO 修改-消耗/获得原因
	 * @param @param request
	 * @param @param response
	 * @param @param typeItem 货币类型
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "changeReason.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void changeReason(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer typeItem,
			String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			Map<String, String> reasonItmes = new LinkedHashMap<>();
			if (typeItem == Integer.parseInt(GameParamConfigManager.getItemsRevise(CommonGameParam.MONEY_TYPE).keySet()
					.toArray()[1].toString())) { // 银两
				reasonItmes.putAll(GameParamConfigManager.getItems(CommonGameParam.MONEY_REASON));
			} else if (typeItem == Integer.parseInt(GameParamConfigManager.getItemsRevise(CommonGameParam.RMB_TYPE)
					.keySet().toArray()[1].toString())) { // 钻石
				reasonItmes.putAll(GameParamConfigManager.getItems(CommonGameParam.RMB_REASON));
			} else if (typeItem == 99999) { // 所有与充值相关的类型
				reasonItmes.putAll(GameParamConfigManager.getItems(CommonGameParam.RMB_REASON));
			} else if (typeItem == -99999) { // 全部
				Map<String, String> t = new LinkedHashMap<>();
				t.put("全部", GameParamConfigManager.ALL_FLAT);
				reasonItmes.putAll(t);
			} else {
				reasonItmes.putAll(GameParamConfigManager.getItems(CommonGameParam.RMB_REASON));

				reasonItmes.putAll(GameParamConfigManager.getItems(CommonGameParam.MONEY_REASON));
			}
			result.put("res", "0");
			result.put("reasonItmes", reasonItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> m = jsonToMap(params);
			Date dateStart = Time.formatDate((String) m.get("dateStart"), "yyyy-MM-dd");
			Date dateEnd = Time.formatDate((String) m.get("dateEnd"), "yyyy-MM-dd");

			String userid = (String) m.get("userid");
			String roleid = (String) m.get("roleid");

			String platform = (String) m.get("platform");
			String channel = (String) m.get("channel");
			String serverid = (String) m.get("serverid");

			Integer currencytype = Integer.valueOf((String) m.get("currencytype"));
			Integer reason = Integer.valueOf((String) m.get("reason"));
			// 开始结束时间不能大于当前时间60天
			if (Time.getInterval(new Date(), dateStart) > 60 || Time.getInterval(new Date(), dateEnd) > 60) {
				result.put("res", "1");
				result.put("msg", "开始结束时间不能小于当前时间60天!");
				printToJson(response, result, callback);
				return;
			}

			// 用户ID，角色ID必要有一个非空
			if (StringUtils.isBlank(userid) && StringUtils.isBlank(roleid)) {
				result.put("res", "1");
				result.put("msg", "用户ID，角色ID必须至少有一个非空!");
				printToJson(response, result, callback);
				return;
			}
			if (HadoopQueryManager.VISIT_QUEUE.offer("MoneyFlowNewAction")) {
				System.out.println("VISIT_QUEUE offer MoneyFlowNewAction ok!");

				StringBuffer sql = new StringBuffer();
				sql.append("select logtime,platform,channel,serverid,userid,roleid,rolelevel,currencytype,reason,param,changenum,leftnum from currency where 1=1 ");
				if (userid != null && !"".equals(userid)) {
					sql.append(" and userid = '");
					sql.append(userid.trim());
					sql.append("' ");
				}
				if (!StringUtils.isBlank(roleid)) {
					sql.append(" and cast(roleid as string) = '");
					sql.append(roleid.trim());
					sql.append("' ");
				}
				if (!"0".equals(platform)) {
					sql.append(" and platform = ");
					sql.append(platform);
				}
				if (!"0".equals(channel)) {
					sql.append(" and channel = '");
					sql.append(channel);
					sql.append("' ");
				}
				if (!"0".equals(serverid)) {
					sql.append(" and serverid = ");
					sql.append(serverid);
				}
				if (currencytype != -99999) {
					if (currencytype == 99999) { // 所有充值相关类型
						ArrayList<String> rcis = new ArrayList<String>(rechargeCurrencyItmes.values());
						if (rcis != null && rcis.size() > 0) {
							sql.append(" and (currencytype = ");
							for (int i = 1; i < rcis.size(); i++) {
								if (i > 1) {
									sql.append(" or currencytype = ");
								}
								sql.append(rcis.get(i));
							}

							sql.append(") ");
						}
					} else {
						sql.append(" and currencytype = ");
						sql.append(currencytype);
					}
				}
				if (reason != -99999) {
					sql.append(" and reason = ");

					// 如果原因小于0，说明原因有重的，这时的处理是：选changenum小于0的
					if (reason < 0) {
						sql.append(-reason);
						sql.append(" and changenum < 0 ");
					} else {
						sql.append(reason);
					}
				}
				sql.append(" and dt >= '");
				sql.append(Time.getDateStr(dateStart));
				sql.append("' and dt <= '");
				sql.append(Time.getDateStr(dateEnd));
				sql.append("' ");
				sql.append(" order by logtime desc ");

				System.out.println(sql.toString());
				Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
				if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()) {
                    result.put("res", new ArrayList<Object[]>());
                    result.put("data", "");
                    printToJson(response, result, callback);
					return;
				}
				List<Object[]> lo = ret.getValue();

				for (Object[] o : lo) {
					o[1] = BiPlatformManager.getPlatformNameById((String) o[1]);
					o[2] = BiPlatformManager.getChannelNameById((String) o[2]);
					o[3] = BiPlatformManager.getServerNameById((String) o[3]);
					Object o7 = o[7];
					o[7] = getMoneyType(o[7]) + "(" + o[7] + ")";
					o[8] = getReasonType(o[8], o7, o[10]) + "(" + o[8] + ")";
					o[9] = getReasonDetailType(o[9], o7) + "(" + o[9] + ")";
				}

				result.put("res", "0");
				result.put("data", lo);
				printToJson(response, result, callback);
			} else {
				System.out.println("VISIT_QUEUE offer MoneyFlowNewAction failed!");
				result.put("res", "1");
				result.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, result, callback);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	private Map<String, String> reasonItmesRevise; // 消耗/获得原因反转
	private Map<String, String> reasonDetailItmesRevise; // 消耗/获得原因细分反转
	private Map<String, String> typeItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.CURRENCY_TYPE); // 货币类型反转

	// 查询消耗/获得类型
	public String getReasonType(Object reasonType, Object currencyType, Object changenum) {
		String key = reasonType == null ? "" : Math.abs(Integer.parseInt(reasonType.toString())) + "";
		String key1 = currencyType == null ? "" : Math.abs(Integer.parseInt(currencyType.toString())) + "";

		if (Integer.parseInt(key1) == Integer.parseInt(GameParamConfigManager
				.getItemsRevise(CommonGameParam.MONEY_TYPE).keySet().toArray()[1].toString())) { // 银两
			reasonItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.MONEY_REASON);
		} else if (Integer.parseInt(key1) == Integer.parseInt(GameParamConfigManager
				.getItemsRevise(CommonGameParam.RMB_TYPE).keySet().toArray()[1].toString())) { // 钻石
			reasonItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.RMB_REASON);
		}

		if (reasonItmesRevise == null) { // 可选列表为空，直接返回
			return key;
		} else {
			int num = Integer.parseInt(changenum.toString()); // 改变值
			String positiveGet = reasonItmesRevise.get(key); // reasonItmesRevise中查询正key，没空表示没配key
			String negativeGet = reasonItmesRevise.get("-" + key); // reasonItmesRevise中查询负key，没空表示没配-key

			if (num < 0 && negativeGet != null) { // 改变值小于0且配了-key才返回negativeGet
				return negativeGet;
			} else {
				return positiveGet == null ? key : positiveGet;
			}
		}
	}

	// 查询消耗/获得细分类型
	public String getReasonDetailType(Object reasonDeailType, Object currencyType) {
		String key = reasonDeailType == null ? "" : Math.abs(Integer.parseInt(reasonDeailType.toString())) + "";
		String key1 = currencyType == null ? "" : Math.abs(Integer.parseInt(currencyType.toString())) + "";

		if (Integer.parseInt(key1) == GameParamConfigManager.getParamType(CommonGameParam.MONEY_TYPE)) { // 银两
			reasonDetailItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.MONEY_DETAIL_REASON);
		} else if (Integer.parseInt(key1) == GameParamConfigManager.getParamType(CommonGameParam.RMB_TYPE)) { // 钻石
			reasonDetailItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.RMB_DETAIL_REASON);
		}

		return (reasonDetailItmesRevise == null || reasonDetailItmesRevise.get(key) == null) ? key
				: reasonDetailItmesRevise.get(key);
	}

	// 元宝类型
	public String getMoneyType(Object currencyType) {
		String key = currencyType == null ? "" : Math.abs(Integer.parseInt(currencyType.toString())) + "";
		return (typeItmesRevise.get(key) == null) ? key : typeItmesRevise.get(key);
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
